$(function () {
    //为单位数日期添加0
    function add0(m) {
        return m < 10 ? '0' + m : m
    };
    /*时间转换格式函数*/
    // function dateFormatter(value) {
    //     return new Date(value).Format("yyyy-MM-dd");
    // }
    function day() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth();
        var d = new Date(year, month, 0);
        return d.getDate();
    }
    /*时间转换格式函数*/
    function formatDate(now) {
        var year = now.getFullYear(),
            month = now.getMonth() + 1,
            date = now.getDate(),
            hour = now.getHours(),
            minute = now.getMinutes(),
            second = now.getSeconds();

        return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
    function formatDay(now) {
        var year = now.getFullYear(),
            month = now.getMonth() + 1,
            date = now.getDate()

        return year + "-" + month + "-" + date;
    }
    //判断session
    $.ajax({
        url: '/session',
        dataType: "json",
        type: "post",
        success: function (data) {
            if(data.code=="1"){
                alert("请先登陆！");
                window.location.href = 'login.html';
            }

        },
        error: function (error) {
           alert("请求错误！");
            window.location.href = 'login.html';
        }

    })

    //select
    $.ajax({
        url: '/food/type',
        dataType: "json",
        type: "post",
        success: function (data) {
            var types=data.data;
            var optionstring = "<option value=\"0\">所有</option>";
            for (var i in types) {
                var jsonObj =types[i];
                optionstring += "<option value=\"" + jsonObj.typeId + "\" >" + jsonObj.typeName + "</option>";
                $("#searchType").html(optionstring);
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    });
    //订单管理初始化
    $("#allOrder").addClass("in active").siblings().removeClass("in active");
    $("#final").click(function() {
        $("#finalOrder").addClass("in active").siblings().removeClass("in active");
    });
    // $("#new").click(function() {
    //     $("#newOrder").addClass("in active").siblings().removeClass("in active");
    // });
    $("#all").click(function() {
        $("#allOrder").addClass("in active").siblings().removeClass("in active");
    });




    //菜品管理初始化
    $("#rfood").addClass("in active").siblings().removeClass("in active");
    //查询所有菜品
    $("#readFood").click(function() {
        $("#rfood").addClass("in active").siblings().removeClass("in active");

        $.ajax({
            url: '/food/show/all',
            dataType: "json",
            type: "post",
            success: function (data) {
                $("#rfood table tbody").empty();
                var types=data.data;
                var imgstring = "";
                for (var i in types) {
                    var jsonObj =types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $("#rfood table tbody").append("<tr>" +
                        "<td><img src=\"http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t3\"/></td>" +
                        "<td>"+jsonObj.foodName+"</td>" +
                        "<td>"+jsonObj.foodType+"</td>" +
                        "<td>"+jsonObj.calorie+"</td>" +
                        "<td>"+jsonObj.price+"</td>" +
                        "<td>"+formatDate(new Date(jsonObj.updateTime))+"</td>" +
                        "<td><button class=\'btn btn-info updateFood\'data-whatever="+jsonObj.foodId+"  data-toggle=\"modal\" data-target=\"#myModal\"  value="+jsonObj.foodId+">更新</button>" +
                        "<button class=\'btn btn-default deleteFood\' id=\'btnd\'  value="+jsonObj.foodId+">删除</button></td>" +
                        "</tr>");
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });
    $("#createFood").click(function() {
        $("#cfood").addClass("in active").siblings().removeClass("in active");
        $.ajax({
            url: '/food/type',
            dataType: "json",
            type: "post",
            success: function (data) {
                var types=data.data;
                var optionstring = "";
                for (var i in types) {
                    var jsonObj =types[i];
                    optionstring += "<option value=\"" + jsonObj.typeId + "\" >" + jsonObj.typeName + "</option>";
                    $("#foodType").html(optionstring);
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });
    $("#addType").click(function() {
        $("#aType").addClass("in active").siblings().removeClass("in active");
    });



    //上传菜品
    $("#sub").click(function(){
        var formData = new FormData($('#uploadFrom')[0]);
        $.ajax({
            url: '/food/up/',
            dataType: "json",
            type: "post",
            contentType: false,
            processData: false,
            async: true,
            data:formData,
            success: function (data) {
                if (data.code == "0") {
                    alert('上传成功');
                    $("#uploadFrom")[0].reset();
                } else if (data.code == "1"){
                    alert('上传失败！');
                }
                else if (data.code == "2"){
                    alert('上传失败！(请使用正确的图片格式.png或.jpg)');
                }
            },
            error: function (error) {
                console.log(error);
                alert("上传请求错误！");
            }
        });
        /*阻止form提交*/
        return false;
    })


//删除菜品
    $('tbody').on('click', '.deleteFood', function () {
        var foodId=$(this).val();
        $.ajax({
            url: '/food/delete/'+foodId,
            dataType: "json",
            type: "post",
            success: function (data) {
                alert("删除成功");
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });

    //更新菜品
    //    绑定模态框展示的方法
    $("#myModal").on("show.bs.modal",function(e){
//        获得点击打开的按钮
        var button=$(e.relatedTarget)
//        根据标签获得按钮传入的参数
        var foodId=button.data("whatever")
//        获得模态框本身
        var modal=$(this)

        $.ajax({
            url: '/food/show/'+foodId,
            dataType: "json",
            type: "post",
            async: false,
            success: function (data) {
                if(data.code="0"){
                    // 更改body里input的值
                    modal.find(".modal-body #modalName").val(data.data.foodName);
                    modal.find(".modal-body #modalPrice").val(data.data.price);
                    modal.find(".modal-body #modalCalorie").val(data.data.calorie);
                    modal.find(".modal-body #modalRemarks").val(data.data.remarks);
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        });

        $.ajax({
            url: '/food/type',
            dataType: "json",
            type: "post",
            async: false,
            success: function (data) {
                var types=data.data;
                var optionstring = "";
                for (var i in types) {
                    var jsonObj =types[i];
                    optionstring += "<option value=\"" + jsonObj.typeId + "\" >" + jsonObj.typeName + "</option>";
                    modal.find(".modal-body #modalType").html(optionstring);
                }
            },
            error: function (error) {
                alert("请求错误！");
            }
        });

        //更新菜品
        $("#foodUpdate").click(function() {
            $.ajax({
                url: '/food/update',
                dataType: "json",
                type: "post",
                data:{
                    foodId: foodId,
                    foodName: function() {
                        return $("#modalName").val();
                    },
                    foodType:function() {
                        return $("#modalType").val();
                    },
                    price:function() {
                        return $("#modalPrice").val();
                    },
                    calorie:function() {
                        return $("#modalCalorie").val();
                    },
                    remarks:function() {
                        return $("#modalRemarks").val();
                    }
                } ,
                success: function (data) {
                    alert("更新成功");
                },
                error: function (error) {
                    alert("请求错误！");
                }

            })
        })
    })


    //上传菜品种类
    $("#sub2").click(function(){
        $.ajax({
            url: '/type/up',
            dataType: "json",
            type: "post",
            async: true,
            data:{
                typeName:function() {
                    return $("#typeName").val();
                },
                typeRemarks:function() {
                    return $("#typeRemarks").val();
                }

            },
            success: function (data) {
                if (data.code == "0") {
                    alert('新增成功');
                    $("#uploadFrom2")[0].reset();
                } else {
                    alert('新增失败！');
                }
            },
            error: function (error) {
                console.log(error);
                alert("上传请求错误！");
            }
        });
        /*阻止form提交*/
        return false;
    });

//指定条件搜索
    $("#searchbtn").click(function() {
        $.ajax({
            url: '/food/show/result',
            dataType: "json",
            type: "post",
            data:{
                foodType:function() {
                    return $("#searchType").val();
                },
                foodName:function() {
                    return $("#searchFood").val();
                }
            },
            success: function (data) {
                $("#rfood table tbody").empty();
                var types=data.data;
                var imgstring = "";
                for (var i in types) {
                    var jsonObj =types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $("#rfood table tbody").append("<tr>" +
                        "<td><img src=\"http://ozul99g6g.bkt.clouddn.com/" + jsonObj.foodImg + "/t3\"/></td>" +
                        "<td>"+jsonObj.foodName+"</td>" +
                        "<td>"+jsonObj.foodType+"</td>" +
                        "<td>"+jsonObj.calorie+"</td>" +
                        "<td>"+jsonObj.price+"</td>" +
                        "<td>"+formatDate(new Date(jsonObj.updateTime))+"</td>" +
                        "<td><button class=\'btn btn-info updateFood\'data-whatever="+jsonObj.foodId+"  data-toggle=\"modal\" data-target=\"#myModal\"  value="+jsonObj.foodId+">更新</button>" +
                        "<button class=\'btn btn-default deleteFood\' id=\'btnd\'  value="+jsonObj.foodId+">删除</button></td>" +
                        "</tr>");
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    })

    //订单显示
    $.ajax({
        url: '/orders/all',
        dataType: "json",
        type: "post",
        success: function (data) {
            $(".ordersTable tbody").empty();
            var types = data.data;
            var imgstring = "";
            for (var i in types) {
                var jsonObj = types[i];
                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                var status="";
                if(jsonObj.status==0){
                    status="等待接单";
                    $(".ordersTable tbody").append("<tr>" +
                        "<td >" + jsonObj.ordersId + "</td>" +
                        "<td>" + jsonObj.phone + "</td>" +
                        "<td>" + jsonObj.username + "</td>" +
                        "<td>￥" + jsonObj.price + "</td>" +
                        "<td>" + jsonObj.addressDetail + "</td>" +
                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                        "<td class=\'st\'>" + status + "</td>" +
                        "<td>" +
                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                        "<td>" +
                        "<button class=\'btn operation\' id=\'btno\'  value=" + jsonObj.ordersId + ">接单</button></td>"+
                        "</tr>");
                }
                else if(jsonObj.status==1){
                    status="已接单";
                    $(".ordersTable tbody").append("<tr>" +
                        "<td >" + jsonObj.ordersId + "</td>" +
                        "<td>" + jsonObj.phone + "</td>" +
                        "<td>" + jsonObj.username + "</td>" +
                        "<td>￥" + jsonObj.price + "</td>" +
                        "<td>" + jsonObj.addressDetail + "</td>" +
                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                        "<td class=\'st\'>" + status + "</td>" +
                        "<td>" +
                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                        "<td>" +
                        "<button class=\'btn btn-success take\' id=\'btno\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                        "</tr>");
                }
                else if(jsonObj.status==2){
                    status="配送中";
                    $(".ordersTable tbody").append("<tr>" +
                        "<td >" + jsonObj.ordersId + "</td>" +
                        "<td>" + jsonObj.phone + "</td>" +
                        "<td>" + jsonObj.username + "</td>" +
                        "<td>￥" + jsonObj.price + "</td>" +
                        "<td>" + jsonObj.addressDetail + "</td>" +
                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                        "<td class=\'st\'>" + status + "</td>" +
                        "<td>" +
                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                        "<td>" +
                        "<button class=\'btn btn-success complete\' id=\'btno\'  value=" + jsonObj.ordersId + ">完成</button></td>"+
                        "</tr>");
                } else if(jsonObj.status==3){
                    status="完成";
                    $(".ordersTable tbody").append("<tr>" +
                        "<td >" + jsonObj.ordersId + "</td>" +
                        "<td>" + jsonObj.phone + "</td>" +
                        "<td>" + jsonObj.username + "</td>" +
                        "<td>￥" + jsonObj.price + "</td>" +
                        "<td>" + jsonObj.addressDetail + "</td>" +
                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                        "<td class=\'st\'>" + status + "</td>" +
                        "<td>" +
                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                        "<td>完成</td>" +
                        "</tr>");
                }

             if(status=="已接单"){
                    $(".st").css({"color":"green"});

                }
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    })

    //显示详情
    $('.ordersTable tbody').on('click', '.ordersDetail', function () {
        var ordersId = $(this).val();
        $.ajax({
            url: '/ordersItem/',
            dataType: "json",
            type: "post",
            data: {
                "ordersId": ordersId
            },
            success: function (data) {
                $(".zyk #ordersIteminfo .ordersItemTable tbody").empty();
                var types = data.data;
                var imgstring = "";
                for (var i in types) {
                    var jsonObj = types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $(".zyk #ordersIteminfo .ordersItemTable tbody").append("<tr>" +
                        "<td>" + jsonObj.foodName + "</td>" +
                        "<td>" + jsonObj.buyNumber + "</td>" +
                        "<td>￥" + jsonObj.totalPrice + "</td>" );
                }
                $(".zyk").css('display', 'block');
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });
    $('.x').click(function () {
        $(".zyk").css('display', 'none');
    })

    //接单
    $('.ordersTable tbody').on('click', '.operation', function () {
        var r = confirm("确认接单吗？");
        var ordersId = $(this).val();
        if (r == true) {
            $.ajax({
                url: '/orders/receive',
                dataType: "json",
                type: "post",
                data: {
                    "ordersId": ordersId
                },
                success: function (data) {

                    //var ordersId = $(this).val();
                    $.ajax({
                        url: '/orders/all',
                        dataType: "json",
                        type: "post",
                        success: function (data) {
                            $(".ordersTable tbody").empty();
                            var types = data.data;
                            var imgstring = "";
                            for (var i in types) {
                                var jsonObj = types[i];
                                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                                var status="";
                                if(jsonObj.status==0){
                                    status="等待接单";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn operation\' id=\'btns\'  value=" + jsonObj.ordersId + ">接单</button></td>"+
                                        "</tr>");
                                }
                                else if(jsonObj.status==1){
                                    status="已接单";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-success take\' id=\'btns\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                                        "</tr>");
                                }    else if(jsonObj.status==2){
                                    status="配送中";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-success complete\' id=\'btns\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                                        "</tr>");
                                }
                                else if(jsonObj.status==3){
                                    status="完成";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>完成</td>" +
                                        "</tr>");
                                }
                              if(status=="已接单"){
                                    $(".st").css({"color":"green"});
                                }
                            }
                        },
                        error: function (error) {
                            alert("请求错误！");
                        }

                    })
                    alert("接单成功！");
                    $(this).css({"background":"#61CC73"});
                },
                error: function (error) {
                    alert("请求错误！");
                }

            })
        }else{
            alert("已取消！");
        }

    });

    //配送
    $('.ordersTable tbody').on('click', '.take', function () {
        var r = confirm("确认配送吗？");
        var ordersId = $(this).val();
        if (r == true) {
            $.ajax({
                url: '/orders/take',
                dataType: "json",
                type: "post",
                data: {
                    "ordersId": ordersId
                },
                success: function (data) {

                    //var ordersId = $(this).val();
                    $.ajax({
                        url: '/orders/all',
                        dataType: "json",
                        type: "post",
                        success: function (data) {
                            $(".ordersTable tbody").empty();
                            var types = data.data;
                            var imgstring = "";
                            for (var i in types) {
                                var jsonObj = types[i];
                                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                                var status="";
                                if(jsonObj.status==0){
                                    status="等待接单";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn operation\' id=\'btns\'  value=" + jsonObj.ordersId + ">接单</button></td>"+
                                        "</tr>");
                                }
                                else if(jsonObj.status==1){
                                    status="已接单";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-success take\' id=\'btns\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                                        "</tr>");
                                }   else if(jsonObj.status==2){
                                    status="配送中";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-success complete\' id=\'btns\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                                        "</tr>");
                                }
                                else if(jsonObj.status==3){
                                    status="完成";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>完成</td>" +
                                        "</tr>");
                                }

                            }
                        },
                        error: function (error) {
                            alert("请求错误！");
                        }

                    })
                },
                error: function (error) {
                    alert("请求错误！");
                }

            })
        }else{
            alert("已取消！");
        }

    });
    //完成
    $('.ordersTable tbody').on('click', '.complete', function () {
        var r = confirm("确认配送完成吗？");
        var ordersId = $(this).val();
        if (r == true) {
            $.ajax({
                url: '/orders/complete',
                dataType: "json",
                type: "post",
                data: {
                    "ordersId": ordersId
                },
                success: function (data) {

                    //var ordersId = $(this).val();
                    $.ajax({
                        url: '/orders/all',
                        dataType: "json",
                        type: "post",
                        success: function (data) {
                            $(".ordersTable tbody").empty();
                            var types = data.data;
                            var imgstring = "";
                            for (var i in types) {
                                var jsonObj = types[i];
                                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                                var status="";
                                if(jsonObj.status==0){
                                    status="等待接单";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn operation\' id=\'btns\'  value=" + jsonObj.ordersId + ">接单</button></td>"+
                                        "</tr>");
                                }
                                else if(jsonObj.status==1){
                                    status="已接单";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-success take\' id=\'btns\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                                        "</tr>");
                                }   else if(jsonObj.status==2){
                                    status="配送中";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-success complete\' id=\'btns\'  value=" + jsonObj.ordersId + ">配送</button></td>"+
                                        "</tr>");
                                }
                                else if(jsonObj.status==3){
                                    status="完成";
                                    $(".ordersTable tbody").append("<tr>" +
                                        "<td >" + jsonObj.ordersId + "</td>" +
                                        "<td>" + jsonObj.phone + "</td>" +
                                        "<td>" + jsonObj.username + "</td>" +
                                        "<td>￥" + jsonObj.price + "</td>" +
                                        "<td>" + jsonObj.addressDetail + "</td>" +
                                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                                        "<td class=\'st\'>" + status + "</td>" +
                                        "<td>" +
                                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                                        "<td>完成</td>" +
                                        "</tr>");
                                }

                            }
                        },
                        error: function (error) {
                            alert("请求错误！");
                        }

                    })
                },
                error: function (error) {
                    alert("请求错误！");
                }

            })
        }else{
            alert("已取消！");
        }

    });

    //已完成订单
    $.ajax({
        url: '/orders/final',
        dataType: "json",
        type: "post",
        success: function (data) {
            $(".finalOrdersTable tbody").empty();
            var types = data.data;
            var imgstring = "";
            for (var i in types) {
                var jsonObj = types[i];
                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $(".finalOrdersTable tbody").append("<tr>" +
                        "<td >" + jsonObj.ordersId + "</td>" +
                        "<td>" + jsonObj.phone + "</td>" +
                        "<td>" + jsonObj.username + "</td>" +
                        "<td>￥" + jsonObj.price + "</td>" +
                        "<td>" + jsonObj.addressDetail + "</td>" +
                        "<td>" + formatDate(new Date(jsonObj.createTime)) + "</td>" +
                        "<td class=\'st\'>" + status + "</td>" +
                        "<td>" +
                        "<button class=\'btn btn-default ordersDetail\' id=\'btnd\'  value=" + jsonObj.ordersId + ">详情</button></td>" +
                        "<td>完成</td>"+
                        "</tr>");
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    })

    //显示详情
    $('.finalOrdersTable tbody').on('click', '.ordersDetail', function () {
        var ordersId = $(this).val();
        $.ajax({
            url: '/ordersItem/',
            dataType: "json",
            type: "post",
            data: {
                "ordersId": ordersId
            },
            success: function (data) {
                $(".zyk #finalOrdersIteminfo .finalOrdersItemTable tbody").empty();
                var types = data.data;
                var imgstring = "";
                for (var i in types) {
                    var jsonObj = types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $(".zyk #finalOrdersIteminfo .finalOrdersItemTable tbody").append("<tr>" +
                        "<td>" + jsonObj.foodName + "</td>" +
                        "<td>" + jsonObj.buyNumber + "</td>" +
                        "<td>￥" + jsonObj.totalPrice + "</td>" );
                }
                $(".zyk").css('display', 'block');
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    });

    //数据统计初始化
    $("#toSell").addClass("in active").siblings().removeClass("in active");
    $("#sell").click(function() {
        $("#toSell").addClass("in active").siblings().removeClass("in active");
    });
    $("#topSell").click(function() {
        $("#tSell").addClass("in active").siblings().removeClass("in active");
    });
    $("#numSell").click(function() {
        $("#nSell").addClass("in active").siblings().removeClass("in active");
    });


    //echarts图表
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));
    option = {
        title: {
            text: '总计'

        },
        tooltip: {
            trigger: 'axis'

        },
        legend: {
            data: ['总计']

        },
        toolbox: {
            show: true,
            feature: {
                dataView: {readOnly: true},
                magicType: {type: ['bar']},
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value} 元'
            }
        },
        series: [
            {
                name: '总计',
                type: 'line',
                smooth: true,
                itemStyle: {
                    normal: {
                        color: '#26AD58'
                    }
                },
                areaStyle: {
                    normal: {
                        color: '#7CCE9A'
                    }
                },
                lineStyle: {
                    normal: {
                        color: '#28AE59'
                    }
                },
                data: [],
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                }
            }

        ]
    };

    myChart.setOption(option);
    var myChart2 = echarts.init(document.getElementById('main2'));
    option2 = {
        title: {
            text: 'TOP10'

        },
        tooltip: {
            trigger: 'axis'

        },
        legend: {
            data: ['总计']

        },
        toolbox: {
            show: true,
            feature: {
                dataView: {readOnly: true},
                magicType: {type: ['bar']},
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value} 份'
            }
        },
        series: [
            {
                name: '总计',
                type: 'line',
                smooth: true,
                itemStyle: {
                    normal: {
                        color: '#F4655F'
                    }
                },
                areaStyle: {
                    normal: {
                        color: '#F3726D'
                    }
                },
                lineStyle: {
                    normal: {
                        color: '#F46964'
                    }
                },
                data: [],
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                }
            }

        ]
    };

    myChart2.setOption(option2);
    var myChart3 = echarts.init(document.getElementById('main3'));
    option3 = {
        title: {
            text: '份数统计'

        },
        tooltip: {
            trigger: 'axis'

        },
        legend: {
            data: ['总计']

        },
        toolbox: {
            show: true,
            feature: {
                dataView: {readOnly: true},
                magicType: {type: ['bar']},
                restore: {},
                saveAsImage: {}
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: []
        },
        yAxis: {
            type: 'value',
            axisLabel: {
                formatter: '{value} 份'
            }
        },
        series: [
            {
                name: '总计',
                type: 'line',
                smooth: true,
                itemStyle: {
                    normal: {
                        color: '#F4655F'
                    }
                },
                areaStyle: {
                    normal: {
                        color: '#F3726D'
                    }
                },
                lineStyle: {
                    normal: {
                        color: '#F46964'
                    }
                },
                data: [],
                markPoint: {
                    data: [
                        {type: 'max', name: '最大值'},
                        {type: 'min', name: '最小值'}
                    ]
                }
            }

        ]
    };
    myChart3.setOption(option3);
    //echarts图表结束
    //json解析函数
    function jsonFormat(data) {
        var statistics = data.data;
        var value = "";
        for (var k in statistics) {//每个key/value对,k为key
            value = value + JSON.stringify(statistics[k]) + ",";
        }
        value = value.substring(0, value.lastIndexOf(','));
        value = "[" + value + "]";
        var jvalue = JSON.parse(value);
        var period="";
        var sell = "";
        var num="";
        for (var v in jvalue) {
            period = period + jvalue[v].period + ",";
            sell = sell + jvalue[v].sell + ",";
            num = num + jvalue[v].num + ",";
        }
        period = period.substring(0, period.lastIndexOf(','));
        sell = sell.substring(0, sell.lastIndexOf(','));
        num = num.substring(0, num.lastIndexOf(','));
        var dataArr = period + "|" + sell+ "|" + num ;
        return dataArr;
    }
    function searchTotal(begin, end) {
        $.ajax({
            url: '/data/totalSell',
            dataType: "json",
            type: "post",
            data: {
                "begin": begin,
                "end":end
            },
            success: function (data) {
                var dataArr = jsonFormat(data);
                dataArr = dataArr.split("|");
                var dateArr = dataArr[0];
                dateArr = dateArr.split(",");
                for (var d = 0; d < dateArr.length; d++) {
                    dateArr[d] = new Date(parseInt(dateArr[d]));
                    dateArr[d] = formatDay(dateArr[d]);
                }
                var sellArr = dataArr[1];
                sellArr = sellArr.split(",");
                var numArr = dataArr[2];
                numArr = numArr.split(",");
                var total = 0;
                for (var i = 0; i < sellArr.length; i++) {
                    total += parseInt(sellArr[i]);
                }
                var totalNum = 0;
                for (var j = 0; j < numArr.length; j++) {
                    totalNum += parseInt(numArr[j]);
                }
                // 填入数据
                myChart.setOption({
                    xAxis: {
                        data: dateArr
                    },
                    series: [{
                        data: sellArr
                    }]
                });
                myChart3.setOption({
                    xAxis: {
                        data: dateArr
                    },
                    series: [{
                        data: numArr
                    }]
                });
                $("#total strong").html(total);
                $("#numTotal strong").html(totalNum);
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    }
    function searchTop(begin, end) {
        $.ajax({
            url: '/data/top',
            dataType: "json",
            type: "post",
            data: {
                "begin": begin,
                "end":end
            },
            success: function (data) {
                var statistics = data.data;
                var value = "";
                for (var k in statistics) {//每个key/value对,k为key
                    value = value + JSON.stringify(statistics[k]) + ",";
                }
                value = value.substring(0, value.lastIndexOf(','));
                value = "[" + value + "]";
                var jvalue = JSON.parse(value);
                var name="";
                var num="";
                for (var v in jvalue) {
                    name = name + jvalue[v].name + ",";
                    num = num + jvalue[v].num + ",";
                }
                name = name.substring(0, name.lastIndexOf(','));
                num = num.substring(0, num.lastIndexOf(','));
                var dataArr = name + "|" + num;
                dataArr = dataArr.split("|");
                var nameArr = dataArr[0];
                nameArr = nameArr.split(",");
                var numArr = dataArr[1];
                numArr = numArr.split(",");
                // 填入数据
                myChart2.setOption({
                    xAxis: {
                        data: nameArr
                    },
                    series: [{
                        data: numArr
                    }]
                });

            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    }
    //自动查询本月数据
    function autoSearch() {
        var date = new Date();
        var begin = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-01" + " " + "00:00:00";
        var end = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-" + add0(date.getDate()) + " " + add0(date.getHours()) + ":" + add0(date.getMinutes()) + ":" + add0(date.getSeconds());
        searchTotal(begin, end);
        searchTop(begin,end);
    }
    autoSearch();
    //点击查询上月数据
    $("#beforemonth").click(function () {
        var date = new Date();
        var a=day();
        date.setMonth(new Date().getMonth() - 1);
        var begin = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-01" + " " + "00:00:00";
        var end = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-"+a+ " " + "23:59:59";
        searchTotal(begin, end);
        searchTop(begin,end);
    });

    //点击查询本月数据
    $("#thismonth").click(function () {
        var date = new Date();
        var begin = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-01" + " " + "00:00:00";
        var end = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-" + add0(date.getDate()) + " " + add0(date.getHours()) + ":" + add0(date.getMinutes()) + ":" + add0(date.getSeconds());
        searchTotal(begin, end);
        searchTop(begin,end);
    });

    //点击查询去年数据
    $("#beforeyear").click(function () {
        var date = new Date();
        date.setFullYear(new Date().getFullYear() - 1);
        var begin = date.getFullYear() + "-01-01" + " " + "00:00:00";
        var end = date.getFullYear() + "-12-31" + " " + "23:59:59";
        searchTotal(begin, end);
        searchTop(begin,end);
    });

    //点击查询本年数据
    $("#thisyear").click(function () {
        var date = new Date();
        var begin = date.getFullYear() + "-01-01" + " " + "00:00:00";
        var end = date.getFullYear() + "-" + add0(date.getMonth() + 1) + "-" + add0(date.getDate()) + " " + add0(date.getHours()) + ":" + add0(date.getMinutes()) + ":" + add0(date.getSeconds());
        searchTotal(begin, end);
        searchTop(begin,end);
    });


    //查询所有用户信息
    $.ajax({
        url: 'user/all',
        dataType: "json",
        type: "post",
        success: function (data) {
            $(".userInfoTable tbody").empty();
            var types=data.data;
            var imgstring = "";
            for (var i in types) {
                var jsonObj =types[i];
                // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                $(".userInfoTable tbody").append("<tr>" +
                    "<td>"+jsonObj.username+"</td>" +
                    "<td>"+jsonObj.phone+"</td>" +
                    "<td>"+jsonObj.password+"</td>" +
                    "<td><button class=\'btn btn-info updateUser\' value="+jsonObj.userId+">更新</button>" +
                    "<button class=\'btn btn-default deleteUser\' id=\'btnd\'  value="+jsonObj.userId+">注销</button></td>" +
                    "</tr>");
            }
        },
        error: function (error) {
            alert("请求错误！");
        }

    })

    //指定条件搜索
    $("#searchbtn2").click(function() {
        $.ajax({
            url: '/user/show/result',
            dataType: "json",
            type: "post",
            data:{
                userInfo:function() {
                    return $("#searchUser").val();
                }
            },
            success: function (data) {
                $(".userInfoTable tbody").empty();
                var types=data.data;
                var imgstring = "";
                for (var i in types) {
                    var jsonObj =types[i];
                    // jsonObj.updateTime=dateFormatter(new Date(parseInt(jsonObj.updateTime)));
                    $(".userInfoTable tbody").append("<tr>" +
                        "<td>"+jsonObj.username+"</td>" +
                        "<td>"+jsonObj.phone+"</td>" +
                        "<td>"+jsonObj.password+"</td>" +
                        "<td><button class=\'btn btn-info updateUser\' value="+jsonObj.userId+">更新</button>" +
                        "<button class=\'btn btn-default deleteUser\' id=\'btnd\'  value="+jsonObj.userId+">注销</button></td>" +
                        "</tr>");
                }
            },
            error: function (error) {
                alert("请求错误！");
            }

        })
    })

    $('.userInfoTable tbody').on('click', '.updateUser', function () {
        var userId = $(this).val();
        $.ajax({
            url: '/user/info',
            dataType: "json",
            type: "post",
            data:{
                userId:userId
            },
            success: function (data) {
                $(".zyk").css('display', 'block');
                var jsonObj=data.data;
                $("#name").val(jsonObj.username);
                $("#pass").val(jsonObj.password);
                $(".up").click(function() {
                    $.ajax({
                        url: '/user/update',
                        dataType: "json",
                        type: "post",
                        data:{
                            userId:userId,
                            username:function() {
                                return $("#name").val();
                            },
                            password:function() {
                                return $("#pass").val();
                            }
                        },
                        success: function (data) {
                            alert("更新成功！");
                        },
                        error: function (error) {
                            alert("请求错误！");
                        }

                    })
                })
            },
            error: function (error) {
                alert("请求错误！");
            }

        })

    });

    $('.userInfoTable tbody').on('click', '.deleteUser', function () {
        var userId = $(this).val();
        var r = confirm("确认注销吗？");
        if (r == true) {
            $.ajax({
                url: '/user/delete',
                dataType: "json",
                type: "post",
                data:{
                    userId:userId
                },
                success: function (data) {
                    alert("注销成功！");
                },
                error: function (error) {
                    alert("请求错误！");
                }

            })
        }
    });
});